/**
 * Copyright (c) 2013 Mark Tielemans
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * DISCLAIMER
 * This software is provided "as is" and any expressed or implied warranties, including, but not limited to, the implied warranties of 
 * merchantability and fitness for a particular purpose are disclaimed. In no event shall the regents or contributors be liable for any 
 * direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute 
 * goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in 
 * contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if 
 * advised of the possibility of such damage.
 */
package test.easydb.mysql;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import nl.marktielemans.easydb.EasyDBConfig;

import org.apache.log4j.Logger;

import test.easydb.EasyDBInitializer;

public class MySQLInitializer implements EasyDBInitializer {

	private static final Logger logger = Logger.getLogger(MySQLInitializer.class);
	private static final String PROPERTIES_FILE = "easydb-test-mysql.properties";
	
	public MySQLInitializer() {
	}
	
	@Override
	public void initialize() throws IOException {
		Properties p = loadProperties();
		EasyDBConfig.get().setDbHostUrl(p.getProperty("db.host.url"));
		EasyDBConfig.get().setDbHostPort(p.getProperty("db.host.port"));
		EasyDBConfig.get().setDbName(p.getProperty("db.name"));
		EasyDBConfig.get().setDbUsername(p.getProperty("db.username"));
		EasyDBConfig.get().setDbPassword(p.getProperty("db.password"));
		EasyDBConfig.get().setDbVendor(p.getProperty("db.vendor"));
		EasyDBConfig.get().setDbDateFormat(p.getProperty("db.date.format"));
		logger.info("Properties loaded");
	}
	
	/**
	 * Load the properties file and read its contents.
	 * @throws IOException
	 */
	private static Properties loadProperties() throws IOException {
		// Get the class loader
        final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        final InputStream inputStream = classLoader.getResourceAsStream(PROPERTIES_FILE);
        if(inputStream == null) {
        	logger.warn("No properties file exists for "+PROPERTIES_FILE);
        	throw new IOException();
        }
        try {
            final Properties p = new Properties();
            p.load(inputStream);
            return p;
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
	}
}
